package com.back.service.impl;

import com.back.entity.FavoriteJob;
import com.back.entity.Job;
import com.back.mapper.FavoriteJobMapper;
import com.back.mapper.JobMapper;
import com.back.service.IFavoriteJobService;
import com.back.vo.JobListVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liyang
 * @since 2025-04-26
 */
@Service
@Slf4j
public class FavoriteJobServiceImpl extends ServiceImpl<FavoriteJobMapper, FavoriteJob> implements IFavoriteJobService {

    @Autowired
    private JobMapper jobMapper;
    
    @Autowired
    private JobServiceImpl jobService;
    
    @Override
    public FavoriteJob addFavorite(Long jobId, Long userId) {
        // 检查是否已收藏
        if (checkFavorite(jobId, userId)) {
            // 已收藏，直接返回
            LambdaQueryWrapper<FavoriteJob> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(FavoriteJob::getUserId, userId)
                     .eq(FavoriteJob::getJobId, jobId)
                     .eq(FavoriteJob::getDeleted, false);
            
            return this.getOne(queryWrapper);
        }
        
        // 检查职位是否存在
        Job job = jobMapper.selectById(jobId);
        if (job == null || job.getDeleted() || !"active".equals(job.getStatus())) {
            throw new RuntimeException("职位不存在或已下线");
        }
        
        // 创建收藏记录
        FavoriteJob favoriteJob = new FavoriteJob();
        favoriteJob.setUserId(userId);
        favoriteJob.setJobId(jobId);
        favoriteJob.setDeleted(false);
        
        long currentTime = System.currentTimeMillis();
        favoriteJob.setCreateTime(currentTime);
        favoriteJob.setUpdateTime(currentTime);
        
        this.save(favoriteJob);
        
        return favoriteJob;
    }
    
    @Override
    public boolean removeFavorite(Long jobId, Long userId) {
        LambdaQueryWrapper<FavoriteJob> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FavoriteJob::getUserId, userId)
                 .eq(FavoriteJob::getJobId, jobId)
                 .eq(FavoriteJob::getDeleted, false);
        
        FavoriteJob favoriteJob = this.getOne(queryWrapper);
        if (favoriteJob == null) {
            return false;
        }
        
        // 逻辑删除
        favoriteJob.setDeleted(true);
        favoriteJob.setUpdateTime(System.currentTimeMillis());
        
        return this.updateById(favoriteJob);
    }
    
    @Override
    public boolean checkFavorite(Long jobId, Long userId) {
        LambdaQueryWrapper<FavoriteJob> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FavoriteJob::getUserId, userId)
                 .eq(FavoriteJob::getJobId, jobId)
                 .eq(FavoriteJob::getDeleted, false);
        
        return this.count(queryWrapper) > 0;
    }
    
    @Override
    public IPage<JobListVO> getUserFavorites(Long userId, Integer page, Integer pageSize) {
        // 分页查询收藏记录
        Page<FavoriteJob> favoriteJobPage = new Page<>(page, pageSize);
        
        LambdaQueryWrapper<FavoriteJob> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FavoriteJob::getUserId, userId)
                 .eq(FavoriteJob::getDeleted, false)
                 .orderByDesc(FavoriteJob::getCreateTime);
        
        IPage<FavoriteJob> favoriteJobIPage = this.page(favoriteJobPage, queryWrapper);
        
        // 转换为JobListVO分页
        Page<JobListVO> resultPage = new Page<>();
        resultPage.setCurrent(favoriteJobIPage.getCurrent());
        resultPage.setSize(favoriteJobIPage.getSize());
        resultPage.setTotal(favoriteJobIPage.getTotal());
        
        // 获取职位ID列表
        List<Long> jobIds = favoriteJobIPage.getRecords().stream()
            .map(FavoriteJob::getJobId)
            .collect(Collectors.toList());
        
        List<JobListVO> jobListVOs = new ArrayList<>();
        
        if (!jobIds.isEmpty()) {
            // 查询职位信息
            LambdaQueryWrapper<Job> jobQueryWrapper = new LambdaQueryWrapper<>();
            jobQueryWrapper.in(Job::getId, jobIds)
                       .eq(Job::getDeleted, false);
            
            List<Job> jobs = jobMapper.selectList(jobQueryWrapper);
            
            // 转换为VO并按收藏时间排序
            for (FavoriteJob favoriteJob : favoriteJobIPage.getRecords()) {
                Job job = jobs.stream()
                    .filter(j -> j.getId().equals(favoriteJob.getJobId()))
                    .findFirst()
                    .orElse(null);
                
                if (job != null) {
                    JobListVO jobListVO = jobService.convertToListVO(job);
                    // 设置收藏时间
                    jobListVO.setFavoriteTime(favoriteJob.getCreateTime());
                    jobListVOs.add(jobListVO);
                }
            }
        }
        
        resultPage.setRecords(jobListVOs);
        
        return resultPage;
    }
}
